home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / dist-packages / DistUpgrade / DistUpgradeViewNonInteractive.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2009-10-12  |  12.0 KB  |  314 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import apt
  5. import logging
  6. import time
  7. import sys
  8. from DistUpgradeView import DistUpgradeView, InstallProgress, FetchProgress
  9. from DistUpgradeConfigParser import DistUpgradeConfig
  10. import os
  11. import pty
  12. import apt_pkg
  13. import select
  14. import fcntl
  15. import string
  16. import re
  17. import subprocess
  18. from subprocess import call, PIPE, Popen
  19. import copy
  20. import apt.progress as apt
  21. from ConfigParser import NoSectionError, NoOptionError
  22.  
  23. class NonInteractiveFetchProgress(FetchProgress):
  24.     
  25.     def updateStatus(self, uri, descr, shortDescr, status):
  26.         FetchProgress.updateStatus(self, uri, descr, shortDescr, status)
  27.         if status == apt.progress.FetchProgress.dlDone:
  28.             print 'fetched %s (%.2f/100) at %sb/s' % (uri, self.percent, apt_pkg.SizeToStr(int(self.currentCPS)))
  29.             if sys.stdout.isatty():
  30.                 sys.stdout.flush()
  31.             
  32.         
  33.  
  34.  
  35.  
  36. class NonInteractiveInstallProgress(InstallProgress):
  37.     
  38.     def __init__(self):
  39.         InstallProgress.__init__(self)
  40.         logging.debug('setting up environ for non-interactive use')
  41.         os.environ['DEBIAN_FRONTEND'] = 'noninteractive'
  42.         os.environ['APT_LISTCHANGES_FRONTEND'] = 'none'
  43.         os.environ['RELEASE_UPRADER_NO_APPORT'] = '1'
  44.         self.config = DistUpgradeConfig('.')
  45.         
  46.         try:
  47.             if self.config.getboolean('NonInteractive', 'ForceOverwrite'):
  48.                 apt_pkg.Config.Set('DPkg::Options::', '--force-overwrite')
  49.         except (NoSectionError, NoOptionError):
  50.             e = None
  51.  
  52.         self.timeout = 2400
  53.         
  54.         try:
  55.             self.timeout = self.config.getint('NonInteractive', 'TerminalTimeout')
  56.         except Exception:
  57.             e = None
  58.  
  59.  
  60.     
  61.     def error(self, pkg, errormsg):
  62.         logging.error("got a error from dpkg for pkg: '%s': '%s'" % (pkg, errormsg))
  63.         environ = copy.copy(os.environ)
  64.         environ['PYCENTRAL'] = 'debug'
  65.         cmd = []
  66.         if 'post-installation' in errormsg:
  67.             prefix = '/var/lib/dpkg/info/'
  68.             name = 'postinst'
  69.             argument = 'configure'
  70.             maintainer_script = '%s/%s.%s' % (prefix, pkg, name)
  71.         elif 'pre-installation' in errormsg:
  72.             prefix = '/var/lib/dpkg/tmp.ci/'
  73.             name = 'preinst'
  74.             argument = 'install'
  75.             maintainer_script = '%s/%s' % (prefix, name)
  76.         elif 'pre-removal' in errormsg:
  77.             prefix = '/var/lib/dpkg/info/'
  78.             name = 'prerm'
  79.             argument = 'remove'
  80.             maintainer_script = '%s/%s.%s' % (prefix, pkg, name)
  81.         elif 'post-removal' in errormsg:
  82.             prefix = '/var/lib/dpkg/info/'
  83.             name = 'postrm'
  84.             argument = 'remove'
  85.             maintainer_script = '%s/%s.%s' % (prefix, pkg, name)
  86.         else:
  87.             print 'UNKNOWN (trigger?) dpkg/script failure for %s (%s) ' % (pkg, errormsg)
  88.             return None
  89.         if not ('post-installation' in errormsg).path.exists(maintainer_script):
  90.             logging.error("can not find failed maintainer script '%s' " % maintainer_script)
  91.             return None
  92.         interp = open(maintainer_script).readline()[2:].strip().split()[0]
  93.         if 'bash' in interp or '/bin/sh' in interp:
  94.             debug_opts = [
  95.                 '-ex']
  96.         elif 'perl' in interp:
  97.             debug_opts = [
  98.                 '-d']
  99.             environ['PERLDB_OPTS'] = 'AutoTrace NonStop'
  100.         else:
  101.             logging.warning("unknown interpreter: '%s'" % interp)
  102.         if '. /usr/share/debconf/confmodule' in open(maintainer_script).read():
  103.             environ['DEBCONF_DEBUG'] = 'developer'
  104.             environ['DEBIAN_HAS_FRONTEND'] = '1'
  105.             interp = '/usr/share/debconf/frontend'
  106.             debug_opts = [
  107.                 'sh',
  108.                 '-ex']
  109.         
  110.         cmd.append(interp)
  111.         cmd.extend(debug_opts)
  112.         cmd.append(maintainer_script)
  113.         cmd.append(argument)
  114.         if name == 'postinst':
  115.             version = Popen('dpkg-query -s %s|grep ^Config-Version' % pkg, shell = True, stdout = PIPE).communicate()[0]
  116.             if version:
  117.                 cmd.append(version.split(':', 1)[1].strip())
  118.             
  119.         elif name == 'preinst':
  120.             pkg = os.path.basename(pkg)
  121.             pkg = pkg.split('_')[0]
  122.             version = Popen('dpkg-query -s %s|grep ^Version' % pkg, shell = True, stdout = PIPE).communicate()[0]
  123.             if version:
  124.                 cmd.append(version.split(':', 1)[1].strip())
  125.             
  126.         
  127.         print cmd
  128.         logging.debug("re-running '%s' (%s)" % (cmd, environ))
  129.         ret = subprocess.call(cmd, env = environ)
  130.         logging.debug('%s script returned: %s' % (name, ret))
  131.  
  132.     
  133.     def conffile(self, current, new):
  134.         logging.warning("got a conffile-prompt from dpkg for file: '%s'" % current)
  135.         time.sleep(5)
  136.         
  137.         try:
  138.             os.write(self.master_fd, 'n\n')
  139.         except Exception:
  140.             e = None
  141.             logging.error("error '%s' when trying to write to the conffile" % e)
  142.  
  143.  
  144.     
  145.     def startUpdate(self):
  146.         InstallProgress.startUpdate(self)
  147.         self.last_activity = time.time()
  148.  
  149.     
  150.     def updateInterface(self):
  151.         if self.statusfd == None:
  152.             return None
  153.         if self.last_activity + self.timeout < time.time():
  154.             logging.warning('no activity %s seconds (%s) - sending ctrl-c' % (self.timeout, self.status))
  155.             os.write(self.master_fd, chr(3))
  156.         
  157.         res = select.select([
  158.             self.statusfd], [], [], 0.1)
  159.         while len(res[0]) > 0:
  160.             self.last_activity = time.time()
  161.             while not self.read.endswith('\n'):
  162.                 self.read += os.read(self.statusfd.fileno(), 1)
  163.                 continue
  164.                 self
  165.             if self.read.endswith('\n'):
  166.                 s = self.read
  167.                 (status, pkg, percent, status_str) = string.split(s, ':')
  168.                 if status == 'pmerror':
  169.                     self.error(pkg, status_str)
  170.                 elif status == 'pmconffile':
  171.                     match = re.compile("\\s*'(.*)'\\s*'(.*)'.*").match(status_str)
  172.                     if match:
  173.                         self.conffile(match.group(1), match.group(2))
  174.                     
  175.                 elif status == 'pmstatus':
  176.                     if float(percent) != self.percent or status_str != self.status:
  177.                         self.statusChange(pkg, float(percent), status_str.strip())
  178.                         self.percent = float(percent)
  179.                         self.status = string.strip(status_str)
  180.                         sys.stdout.write('[%s] %s: %s\n' % (float(percent), pkg, status_str.strip()))
  181.                         sys.stdout.flush()
  182.                     
  183.                 
  184.             
  185.             self.read = ''
  186.             res = select.select([
  187.                 self.statusfd], [], [], 0.1)
  188.         res = select.select([
  189.             self.master_fd], [], [], 0.1)
  190.         while len(res[0]) > 0:
  191.             self.last_activity = time.time()
  192.             
  193.             try:
  194.                 s = os.read(self.master_fd, 1)
  195.                 sys.stdout.write('%s' % s)
  196.             except OSError:
  197.                 e = None
  198.                 return None
  199.  
  200.             res = select.select([
  201.                 self.master_fd], [], [], 0.1)
  202.         sys.stdout.flush()
  203.  
  204.     
  205.     def fork(self):
  206.         logging.debug('doing a pty.fork()')
  207.         os.environ['TERM'] = 'dumb'
  208.         (self.pid, self.master_fd) = pty.fork()
  209.         if self.pid != 0:
  210.             logging.debug('pid is: %s' % self.pid)
  211.         
  212.         return self.pid
  213.  
  214.  
  215.  
  216. class DistUpgradeViewNonInteractive(DistUpgradeView):
  217.     ''' non-interactive version of the upgrade view '''
  218.     
  219.     def __init__(self, datadir = None, logdir = None):
  220.         self.config = DistUpgradeConfig('.')
  221.         self._fetchProgress = NonInteractiveFetchProgress()
  222.         self._installProgress = NonInteractiveInstallProgress()
  223.         self._opProgress = apt.progress.OpProgress()
  224.         sys.__excepthook__ = self.excepthook
  225.  
  226.     
  227.     def excepthook(self, type, value, traceback):
  228.         ''' on uncaught exceptions -> print error and reboot '''
  229.         logging.error("got exception '%s': %s " % (type, value))
  230.         self.confirmRestart()
  231.  
  232.     
  233.     def getOpCacheProgress(self):
  234.         ''' return a OpProgress() subclass for the given graphic'''
  235.         return self._opProgress
  236.  
  237.     
  238.     def getFetchProgress(self):
  239.         ''' return a fetch progress object '''
  240.         return self._fetchProgress
  241.  
  242.     
  243.     def getInstallProgress(self, cache = None):
  244.         ''' return a install progress object '''
  245.         return self._installProgress
  246.  
  247.     
  248.     def updateStatus(self, msg):
  249.         ''' update the current status of the distUpgrade based
  250.             on the current view
  251.         '''
  252.         pass
  253.  
  254.     
  255.     def setStep(self, step):
  256.         ''' we have 5 steps current for a upgrade:
  257.         1. Analyzing the system
  258.         2. Updating repository information
  259.         3. Performing the upgrade
  260.         4. Post upgrade stuff
  261.         5. Complete
  262.         '''
  263.         pass
  264.  
  265.     
  266.     def confirmChanges(self, summary, changes, downloadSize, actions = None, removal_bold = True):
  267.         DistUpgradeView.confirmChanges(self, summary, changes, downloadSize, actions)
  268.         logging.debug("toinstall: '%s'" % self.toInstall)
  269.         logging.debug("toupgrade: '%s'" % self.toUpgrade)
  270.         logging.debug("toremove: '%s'" % self.toRemove)
  271.         return True
  272.  
  273.     
  274.     def askYesNoQuestion(self, summary, msg):
  275.         """ ask a Yes/No question and return True on 'Yes' """
  276.         return True
  277.  
  278.     
  279.     def confirmRestart(self):
  280.         ''' generic ask about the restart, can be overridden '''
  281.         logging.debug('confirmRestart() called')
  282.         
  283.         try:
  284.             return self.config.getboolean('NonInteractive', 'RealReboot')
  285.         except Exception:
  286.             e = None
  287.             logging.debug('no RealReboot found, returning false (%s) ' % e)
  288.             return False
  289.  
  290.  
  291.     
  292.     def error(self, summary, msg, extended_msg = None):
  293.         ''' display a error '''
  294.         logging.error('%s %s (%s)' % (summary, msg, extended_msg))
  295.  
  296.     
  297.     def abort(self):
  298.         logging.error('view.abort called')
  299.  
  300.  
  301. if __name__ == '__main__':
  302.     view = DistUpgradeViewNonInteractive()
  303.     fp = NonInteractiveFetchProgress()
  304.     ip = NonInteractiveInstallProgress()
  305.     ip.error('xserver-xorg', 'pre-installation script failed')
  306.     cache = apt.Cache()
  307.     for pkg in sys.argv[1:]:
  308.         cache[pkg].markInstall()
  309.     
  310.     cache.commit(fp, ip)
  311.     time.sleep(2)
  312.     sys.exit(0)
  313.  
  314.